
import React, { useEffect } from 'react';
import { BrowserRouter, Routes, Route, Navigate, Outlet, useParams } from 'react-router-dom';
import { LocalizationProvider } from './contexts/LocalizationContext';
import { useLocalization } from './hooks/useLocalization';
import { SUPPORTED_LANGS, TOOLS } from './constants';
import Header from './components/Header';
import Footer from './components/Footer';
import HomePage from './pages/HomePage';
import ToolPage from './pages/ToolPage';
import FaqPage from './pages/FaqPage';
import StaticPage from './pages/StaticPage';
import CookieConsent from './components/CookieConsent';
import NotFoundPage from './pages/NotFoundPage';

// This layout handles language state and renders the common page structure.
const AppLayout: React.FC = () => {
    // Parameters can be {lang: 'es', tool: 'instagram-downloader'} or {tool: 'es'} or {tool: 'instagram-downloader'}
    const params = useParams<{ lang?: string, tool?: string }>();
    const { setLanguage } = useLocalization();

    useEffect(() => {
        // The primary source for language is the ':lang' parameter from routes like /:lang/faq
        let detectedLang = params.lang;

        // If ':lang' is not in the URL (e.g., path is '/<something>'), we check if that 
        // 'something' (which is passed as the 'tool' param from the root route)
        // is actually a language code. This handles /es, /de, etc.
        if (!detectedLang && params.tool && SUPPORTED_LANGS.some(l => l.code === params.tool)) {
            detectedLang = params.tool;
        }

        // If we found a valid language code, use it. Otherwise, default to 'en'.
        const effectiveLang = detectedLang && SUPPORTED_LANGS.some(l => l.code === detectedLang) ? detectedLang : 'en';
        setLanguage(effectiveLang);
        document.documentElement.lang = effectiveLang;
    }, [params, setLanguage]);

    return (
        <div className="flex flex-col min-h-screen bg-light dark:bg-gray-900 text-dark dark:text-light">
            <Header />
            <main className="flex-grow">
                <Outlet />
            </main>
            <Footer />
            <CookieConsent />
        </div>
    );
};

// This component inspects the first path segment and decides which page to show.
// It's used for paths like /instagram-downloader or /es to avoid route ambiguity.
const RootDispatcher: React.FC = () => {
    // The parameter from the route <Route path=":tool" ...> is named 'tool', which is the slug.
    const { tool: slug } = useParams<{ tool: string }>();

    // If 'slug' parameter is a valid language, it's a homepage for that lang (e.g., /es).
    if (slug && SUPPORTED_LANGS.some(l => l.code === slug)) {
        return <HomePage />;
    }

    // If 'slug' parameter is a valid tool slug, it's a tool page (e.g., /instagram-downloader).
    if (slug && TOOLS.some(t => t.slug === slug)) {
        return <ToolPage />;
    }

    // If it's neither, it's a 404 page.
    return <NotFoundPage />;
};

const App: React.FC = () => {
  return (
    <LocalizationProvider>
      <BrowserRouter>
        <Routes>
          {/* All routes are wrapped in the layout to provide consistent UI and language context */}
          <Route path="/" element={<AppLayout />}>
            {/* English Homepage */}
            <Route index element={<HomePage />} />
            
            {/* English Static Pages */}
            <Route path="faq" element={<FaqPage />} />
            <Route path="contact" element={<StaticPage pageKey="contact" />} />
            <Route path="terms-of-service" element={<StaticPage pageKey="terms" />} />
            <Route path="privacy-policy" element={<StaticPage pageKey="privacy" />} />
            
            {/* This handles root-level dynamic paths like /instagram-downloader OR /es */}
            {/* The parameter is named 'tool' and RootDispatcher will figure out what it is. */}
            <Route path=":tool" element={<RootDispatcher />} />
          </Route>
          
          {/* Language-prefixed routes for nested pages */}
          {/* Note: The root of a language (e.g. /es) is handled by the RootDispatcher above. */}
          <Route path="/:lang" element={<AppLayout />}>
            <Route path="faq" element={<FaqPage />} />
            <Route path="contact" element={<StaticPage pageKey="contact" />} />
            <Route path="terms-of-service" element={<StaticPage pageKey="terms" />} />
            <Route path="privacy-policy" element={<StaticPage pageKey="privacy" />} />
            
            {/* Handles /:lang/:tool */}
            <Route path=":tool" element={<ToolPage />} />

            {/* Handles unmatched language-prefixed routes like /en/nonexistent */}
            <Route path="*" element={<NotFoundPage />} />
          </Route>

          {/* Fallback for any other route not matching above, wrapped in layout */}
          <Route path="*" element={<AppLayout />}>
              <Route path="*" element={<NotFoundPage />} />
          </Route>
        </Routes>
      </BrowserRouter>
    </LocalizationProvider>
  );
};

export default App;